<template>
  <div>
    <SearchForm @search="getTableData" @reset="clearSearch">
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('角色名称')">
          <el-input v-model="page.name"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('状态')">
          <el-select style="width:100%" v-model="page.status" clearable>
            <el-option :label="$t('启用')" :value="1"></el-option>
            <el-option :label="$t('禁用')" :value="0"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
    </SearchForm>
    <!--     表格-->
    <el-card shadow="never" style="margin-top: 10px">
      <el-row>
        <el-button @click="addRole" v-show="$permiss[6]" type="primary" style="float: right">
          {{ $t('新增角色') }}
        </el-button>
      </el-row>
      <el-row style="margin-top: 10px">
        <Table :table-column="tableColumn" :table-data="tableData" row-key="id" :page="page"
               @handleSizeChange="handleSizeChange"
               @handleCurrentChange="handleCurrentChange">
          <template slot="first">
            <el-table-column :label="$t('角色名称')" :prop="roleName" align="center"></el-table-column>
          </template>
          <template slot-scope="scope" slot="status">
            <el-switch :disabled="!$permiss[9]" @change="changeStatus(scope.row)"
                       :value="scope.row.status"></el-switch>
          </template>
          <template slot="handle" slot-scope="{row}">
            <el-button :disabled="!row.status" type="text" v-show="$permiss[7]"
                       @click="editRole(row)"
            >{{ $t('编辑') }}
            </el-button>
            <el-button type="text" v-show="$permiss[1023]"
                       @click="clickRows(row)"
            >{{ $t('登录IP限制') }}
            </el-button>
          </template>
        </Table>
      </el-row>
    </el-card>
    <!--    弹窗-->
    <Dialog @confirm="visibleConfirm" @cancel="visibleRole = false" @close="clearForm" :visible.sync="visibleRole"
            :title="visibleTitle">
      <el-form :model="form" :rules="rulesForm" ref="form" label-width="100px">
        <el-form-item :label="$t('角色名称') +' :'" prop="roleName">
          <el-input v-model="form.roleName"></el-input>
        </el-form-item>
        <el-form-item v-show="$permiss[107]" :label="$t('权限配置')+ ' :'">
          <el-row :gutter="24">
            <el-col :span="24" v-loading="treeLoading">
              <el-tree
                  :props="{label:'name'}"
                  node-key="id"
                  show-checkbox
                  ref="tree"
                  :data="treeData"
              >
              </el-tree>
            </el-col>

          </el-row>
        </el-form-item>
        <el-form-item :label="$t('备注') + ' :'">
          <el-input :rows="4" v-model="form.remark" type="textarea"></el-input>
        </el-form-item>
      </el-form>
    </Dialog>
    <!--    登录ip限制-->
    <LoginPlace :visible.sync="visibleIpPlace" :rows="tableRows"></LoginPlace>
  </div>
</template>

<script>
import {deepClone, formaterTree} from "@/utils/tools";
import LoginPlace from "./loginPlace";
import qs from 'qs'
import {
  roleUpdateStatus,
  fetchRole,
  roleInsert,
  fetchLowerRole,
  roleUpdate,
  fetchMenuList,
  selectConfigPermission
} from "@/api/system";

export default {
  name: 'roleManagement',
  data() {
    return {
      page: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      form: {
        roleName: '',
        remark: ''
      },
      dialogType: '',
      tableColumn: [
        {label: this.$t('创建人'), prop: 'inputName', align: 'center'},
        {label: this.$t('创建时间'), prop: 'createTime', align: 'center'},
        {label: this.$t('备注'), prop: 'remark', align: 'center'},
        {label: this.$t('状态'), slot: 'status', align: 'center', width: 100},
        {
          label: this.$t('操作'),
          slot: 'handle',
          align: 'center',
          width: 150,
          isHide: !this.$permiss[1022]
        },
      ],
      rulesForm: {
        roleName: [
          {required: true, message: this.$t('请输入角色名称'), trigger: 'blur'}
        ],
        languageName: [
          {required: true, message: this.$t('请输入国际名称'), trigger: 'blur'}
        ],
      },
      tableData: [],
      visibleRole: false,
      treeLoading: false,
      visibleTitle: '',
      treeData: [],
      visibleIpPlace: false,
      tableRows: {},
    }
  },
  components: {
    LoginPlace
  },
  computed: {
    roleName() {
      return this.$i18n.locale === 'zh_CN' ? 'name' : 'languageName'
    }
  },
  mounted() {
    this.getTableData()
  },
  methods: {
    async getTableData() {
      const params = {
        ...this.page
      }
      const res = await fetchRole(params)
      if (res.code === 1) {
        const {list, pageNum, total} = res.data
        const data = list.map(item => {
          item.status = item.status === 1
          return item
        })
        this.tableData = data
        this.page = Object.assign({}, this.page, {
          page: pageNum,
          total: total
        })
      }
    },
    handleCurrentChange(val) {
      this.page.pageNum = val
      this.getTableData()
    },
    handleSizeChange(val) {
      this.page.pageSize = val
      this.getTableData()
    },

    clearSearch() {
      this.page = {
        pageNum: 1,
        pageSize: 10,
        total: 0
      }
      this.getTableData()
    },
    clearForm() {
      this.treeData = []
      this.form = {}
      this.$refs.form.resetFields()
    },
    async addRole() {
      this.dialogType = 'add'
      this.visibleTitle = this.$t('新增角色')
      this.visibleRole = true
      this.treeLoading = true
      const list = await this.getMenuList()
      this.treeLoading = false
      this.treeData = list
    },
    async editRole(row) {
      this.visibleRole = true
      this.visibleTitle = this.$t('编辑角色')
      this.treeLoading = true
      this.dialogType = 'edit'
      this.form = {
        roleName: row.name,
        languageName: row.languageName,
        remark: row.remark ? row.remark : '',
        id: row.id
      }
      const params = {
        type: row.type,
        rid: row.id
      }
      const res = await selectConfigPermission(qs.stringify(params),)
      if (res.code === 1) {
        this.treeData = formaterTree(deepClone(res.data.map(item => {
          return {
            name: item.name,
            parentId: item.parentId,
            id: item.id
          }
        })))
        this.$nextTick(() => {
          const keys = res.data.filter(item => item.checked).map(item => item.id).sort((a, b) => a - b)
          keys.forEach(item => {
            this.$refs.tree.setChecked(item, true)
          })
          this.treeLoading = false
        })
      }
    },

    clickRows(row) {
      this.visibleIpPlace = true
      this.tableRows = {...row}
    },
    async getMenuList() {
      const res = await fetchMenuList()
      if (res.code === 1) {
        return formaterTree(res.data)
      }
    },
    // 弹出框确认回调
    visibleConfirm() {
      const treeKeys = [...this.$refs.tree.getCheckedKeys(), ...this.$refs.tree.getHalfCheckedKeys()]
      this.$refs.form.validate(async v => {
        if (v) {
          const params = {
            roleName: this.form.roleName,
            remark: this.form.remark,
            pids: treeKeys
          }
          let message = ''
          let api
          if (this.dialogType === 'add') {
            api = roleInsert(params)
            message = this.$t('新增成功')
          } else {
            message = this.$t('修改成功')
            params.rid = this.form.id
            api = roleUpdate(params)
          }
          const res = await api
          if (res.code === 1) {
            this.$message.success(message)
            this.visibleRole = false
            this.getTableData()
          }
        }
      })

    },
    // 切换角色状态
    async changeStatus(row) {
      const res = await roleUpdateStatus({rid: row.id})
      if (res.code === 1) {
        this.$message.success(this.$t('修改成功'))
        this.getTableData()
      }
    },
  }
}
</script>

<style scoped>

</style>
